package cn.hxzy.filter;


import cn.hxzy.config.AuthProperties;
import cn.hxzy.util.JwtUtils;
import com.aliyun.oss.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Order(0)
public class AuthorizeFilter implements GlobalFilter {

    @Autowired
    private AuthProperties authProperties;

    //路径匹配器
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1、获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2、判断是否要做登录拦截
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }
        //3、获取token
        String token = null;
        List<String> headers = request.getHeaders().get("Authorization");
        if (headers != null && !headers.isEmpty()) {
            token = headers.get(0);
        }

        //4、校验并解析token
        String userId = null;
        try {
            userId = JwtUtils.getUserIdFromToken(token);
            if (StringUtils.isNullOrEmpty(userId)){
                throw new RuntimeException();
            }
        } catch (Exception e) {
            //校验失败，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //拦截，终止,后续所有的拦截器就不会再执行了，请求也不会转发了
            return response.setComplete();
        }
        String userInfo=userId.toString();
        //5、传递用户信息
        ServerWebExchange swe = exchange
                .mutate().request(builder -> {
                    builder.header("user-info", userInfo);
                }).build();
        //6、放行
        return chain.filter(swe);
    }

    //判断路由的是否需要放行
    private boolean isExclude(String path) {
        for (String item:authProperties.getExcludePaths()){
            if(antPathMatcher.match(item,path)){
                return true;
            }
        }
        return false;
    }
}
